<?php

namespace Icsoc\DataBundle\Model;

use Doctrine\DBAL\DBALException;
use Icsoc\CoreBundle\Logger\ActionLogger;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Class AgentModel
 *
 * @package Icsoc\DataBundle\Model
 */
class AgentModel extends BaseModel
{
    /** @var array 坐席类型,-1 =>非坐席，0=>普通坐席,1=>班长坐席 */
    protected $agRoles = array(-1, 0, 1);

    /** @var ContainerInterface */
    public $container;

    /** @var \Doctrine\DBAL\Connection */
    private $conn;

    /**
     * 坐席电话呼叫状态
     */
    const FORBIDDEN_CALL_IN_AND_OUT = 0;
    const ALLOWED_CALL_IN = 1;
    const ALLOWED_CALL_OUT = 2;
    const ALLOWED_CALL_IN_AND_OUT = 3;

    /**
     * @var array
     */
    private $callStatus = array(
        self::FORBIDDEN_CALL_IN_AND_OUT,
        self::ALLOWED_CALL_IN,
        self::ALLOWED_CALL_OUT,
        self::ALLOWED_CALL_IN_AND_OUT,
    );

    /**
     * 参数对应的要更新的数据库的值
     *
     * @var array
     */
    private $callStatusValue = array(
        self::FORBIDDEN_CALL_IN_AND_OUT => 0x000f,
        self::ALLOWED_CALL_IN => 0x0007,
        self::ALLOWED_CALL_OUT => 0x000b,
        self::ALLOWED_CALL_IN_AND_OUT => 0x0003,
    );

    /**
     * @param ContainerInterface $container
     */
    public function __construct(ContainerInterface $container)
    {
        $this->container = $container;
        $this->conn = $this->container->get('doctrine.dbal.default_connection');
    }

    /**
     * 静态坐席签入
     *
     * @param array $param 签入参数，格式为
     *                     array(
     *                         vcc_id,//企业id
     *                         vcc_code,//企业代码
     *                         data = array(
     *                             array(
     *                             ag_num,//坐席工号
     *                             phone,//分机号
     *                           )
     *                        )
     *                     )
     *
     * @return array
     */
    public function staticAgentLogin(array $param = array())
    {
        //$user = $this->container->get("security.token_storage")->getToken()->getUser();
        if (empty($param)) {
            $ret = array(
                'code' => 415,
                'message' => '参数data不能为空',
            );

            return $ret;
        }
        $vccId = isset($param['vcc_id']) ? $param['vcc_id'] : '';
        $vccCode = isset($param['vcc_code']) ? $param['vcc_code'] : '';
        $dataArray = isset($param['data']) ? $param['data'] : '';
        if (empty($vccId) && empty($vccCode)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID或企业代码都为空',
            );

            return $ret;
        }

        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->container->get('doctrine.dbal.default_connection');
        if (empty($vccId) && !empty($vccCode)) {
            //根据vcc_code 查出vcc_id;
            $vccId = $conn->fetchColumn(
                " SELECT vcc_id FROM win_agent WHERE vcc_code = :vcc_code AND is_del=0 LIMIT 1 ",
                array('vcc_code' => $vccCode)
            );
        }

        if (!is_numeric($vccId)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符或企业代码不存在',
            );

            return $ret;
        }
        if (empty($dataArray)) {
            $ret = array(
                'code' => 404,
                'message' => '参数中详细数据data为空',
            );

            return $ret;
        }
        if (!is_array($dataArray)) {
            $ret = array(
                'code' => 405,
                'message' => '参数中详细数据data格式不对，要求为数组',
            );

            return $ret;
        }

        /** @var array $successJudge 存放正确结果判断的数组 */
        $successJudge = array();
        /** @var array $errorJudge 存放失败结果判断的数组 */
        $errorJudge = array();
        $address = $this->container->get('icsoc_core.common.class')->newGetWinIp();
        //$address = $user->getWinIp();
        $port = $this->container->getParameter('win_socket_port');
        $logger = $this->container->get('logger');
        $localCode = $this->container->getParameter('local_code');
        foreach ($dataArray as $value) {
            if (!is_array($value)) {
                $errorJudge[] = array(
                    'code' => 405,
                    'message' => '参数中详细数据data格式不对，要求为数组',
                    'data' => $value,
                );
                continue;
            }
            if (!array_key_exists('ag_num', $value) || !array_key_exists('phone', $value)) {
                $errorJudge[] = array(
                    'code' => 406,
                    'message' => '参数中详细数据data数组格式不对，必须包含工号ag_num和分机号phone',
                    'data' => $value,
                );
                continue;
            }

            $homeTown = $res = $this->container->get("icsoc_data.model.location")->getNumberloc($value['phone']);
/*            if ($res['code'] != 200) {
                $errorJudge[] = array(
                    'code' => 420,
                    'message' => '归属地查询失败',
                );
                continue;
            }*/

            $haveing = $conn->fetchColumn(
                "SELECT id FROM win_phone WHERE pho_num = :pho_num AND vcc_id = :vcc_id",
                array('pho_num' => $value['phone'], 'vcc_id' => $vccId)
            );
            $selectPhone = $value['phone'];
            if (empty($haveing)) {
                $addData = array();
                $addData['vcc_code'] = $vccCode;
                $addData['passtype'] = 1;
                if (strlen($value['phone']) >= 7) {
                    $addData['pho_type'] = 1;

                    if ($res['data']['type'] == 'MOBILE') {
                        if ($res['data']['code'] != $localCode) {
                            $addData['pho_num'][] = $selectPhone = '0'.$res['data']['realPhone'];
                        } else {
                            $addData['pho_num'][] = $selectPhone = $res['data']['realPhone'];
                        }
                    } else {
                        $addData['pho_num'][] = $value['phone'];
                    }
                } else {
                    $errorJudge[] = array(
                        'code' => 418,
                        'message' => '分机号格式不正确',
                        'data' => $value,
                    );
                    continue;
                }
                $msg = $this->container->get('icsoc_data.model.phone')->add($addData);
                if ($msg['code'] != 200) {
                    $errorJudge[] = array(
                        'code' => 419,
                        'message' => '添加分机失败',
                    );
                    continue;
                }
            }
            $info = $conn->fetchAll(
                "SELECT a.vcc_id,a.id ag_id,a.ag_num,a.ag_name,a.group_id,getagqu(a.id) agqu,b.id phone_id,
                  b.pho_num pho_num, b.pho_type,b.pho_pass ,b.pho_chan , a.ag_owncaller, a.tellevel
                  FROM win_agent a
                  LEFT JOIN win_phone b ON a.vcc_id=b.vcc_id AND b.pho_num = :pho_num
                  WHERE a.is_del=0 AND a.ag_num = :ag_num AND a.vcc_id = :vcc_id ",
                array('pho_num' => $selectPhone, 'ag_num' => $value['ag_num'], 'vcc_id' => $vccId)
            );

            if (empty($info)) {
                $errorJudge[] = array(
                    'code' => 409,
                    'message' => '分机号不存在',
                    'data' => $value,
                );
                continue;
            }

            // 处理坐席名中的特殊字符
            $info[0]['ag_name'] = str_replace('(', '（', $info[0]['ag_name']);
            $info[0]['ag_name'] = str_replace(')', '）', $info[0]['ag_name']);
            $info[0]['ag_name'] = str_replace('|', '', $info[0]['ag_name']);

//            if (function_exists('mb_convert_encoding')) {
//                $ag_name = mb_convert_encoding($info[0]['ag_name'], "GBK", "UTF-8");
//            } else {
//                $ag_name = iconv("UTF-8", "GBK", $info[0]['ag_name']);
//            }
            $agquInfo = explode(',', rtrim($info[0]['agqu'], ","));
            $queInfo = array();
            foreach ($agquInfo as $val) {
                $queArray = explode('-', $val);
                foreach ($queArray as $queKey => $queValue) {
                    $queArray[$queKey] = intval($queValue);
                }
                $queInfo[] = $queArray;
            }

            $arr = array(
                'cli' => "aglogin",
                'ret' => 0,
                'vccid' => intval($info[0]['vcc_id']),
                'agid' => intval($info[0]['ag_id']),
                'agnum' => $info[0]['ag_num'],
                'agname' => $info[0]['ag_name'],
                'phoid' => intval($info[0]['phone_id']),
                'photype' => intval($info[0]['pho_type']),
                'phonum' => $info[0]['pho_num'],
                'photrunk' => $info[0]['pho_chan'],
                'phopass' => $info[0]['pho_pass'],
                'queinfo' => $queInfo,
                'owncaller' => $info[0]['ag_owncaller'],
                'tellevel' => intval($info[0]['tellevel']),
                'gid' => intval($info[0]['group_id']),
                'pho_acode' => "",
                'pho_aname' => "",
                'pho_type' => "",
                'pho_vendor' => "",
                'pho_proxy' => "",
            );
            if ($arr['photype'] == 5) {
                //从reids 读取；
                $redisKey = sprintf('sip.ss%sss%s', $arr['vccid'], $arr['agnum']);
                $ivrInfo = $this->container->get('snc_redis.sip')->hget($redisKey, 'id');
                if (!empty($ivrInfo)) {
                    $arr['pho_proxy'] = $ivrInfo;
                    $arr['pho_type'] = 'ICSOC';
                }
            }
            if (!empty($homeTown) && $info[0]['pho_type'] == 1) {
                $arr['pho_acode'] = $homeTown['data']['code'];
                $arr['pho_aname'] = $homeTown['data']['city'];
                $arr['pho_type'] = $homeTown['data']['type'];
                $arr['pho_vendor'] = '';
            }
            $str = json_encode($arr);
            $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
            if ($socket === false) {
                $errorCode = socket_last_error();
                $errorMsg = socket_strerror($errorCode);
                $logger->error('无法创建socket：【'.$errorCode.'】'.$errorMsg);
                $errorJudge[] = array(
                    'code' => 416,
                    'message' => '签入失败',
                    'data' => $value,
                );
                continue;
            }
            $res = @socket_connect($socket, $address, $port);
            //连接失败
            if ($res === false) {
                $errorCode = socket_last_error();
                $errorMsg = socket_strerror($errorCode);
                $logger->error('socket无法连接到【'.$address.':'.$port.'】：【'.$errorCode.'】'.$errorMsg);
                $errorJudge[] = array(
                    'code' => 416,
                    'message' => '签入失败',
                    'data' => $value,
                );
                continue;
            }
            $str .= "\r\n\r\n";
            $res = @socket_write($socket, $str, strlen($str));
            //发送数据失败
            if ($res === false) {
                $errorCode = socket_last_error();
                $errorMsg = socket_strerror($errorCode);
                $logger->error('socket发送数据失败：【'.$errorCode.'】'.$errorMsg);
                $errorJudge[] = array(
                    'code' => 416,
                    'message' => '签入失败',
                    'data' => $value,
                );
                continue;
            }
            $responce = socket_read($socket, 100);
            if (strstr($responce, 'Success')) {
                //记录 成功一个
                $successJudge[] = array(
                    'code' => 200,
                    'message' => 'ok',
                    'data' => $value,
                );
                // make_json_result(1);
            } elseif ($responce === false) {
                //如果出现无法连接服务器
                $errorCode = socket_last_error();
                $errorMsg = socket_strerror($errorCode);
                $logger->error('socket读取数据失败：【'.$errorCode.'】'.$errorMsg);
                $errorJudge[] = array(
                    'code' => 416,
                    'message' => '签入失败',
                    'data' => $value,
                );
            } else {
                // $errname = $responce;
                $responce = explode("\r\n", $responce);
                if (isset($responce[1])) {
                    $errcode = explode(":", $responce[1]);
                    if (isset($errcode[1])) {
                        switch (trim($errcode[1])) {
                            case '1':
                                $errorJudge[] = array(
                                    'code' => 407,
                                    'message' => '坐席已初始化',
                                    'data' => $value,
                                );
                                break;
                            case '2':
                                $errorJudge[] = array(
                                    'code' => 408,
                                    'message' => '本Socket已初始化',
                                    'data' => $value,
                                );
                                break;
                            case '3':
                                $errorJudge[] = array(
                                    'code' => 409,
                                    'message' => '分机号不存在',
                                    'data' => $value,
                                );
                                break;
                            case '4':
                                $errorJudge[] = array(
                                    'code' => 410,
                                    'message' => '分机已有坐席使用',
                                    'data' => $value,
                                );
                                break;
                            case '5':
                                $errorJudge[] = array(
                                    'code' => 411,
                                    'message' => '有队列不存在',
                                    'data' => $value,
                                );
                                break;
                            case '6':
                                $errorJudge[] = array(
                                    'code' => 412,
                                    'message' => '已达登录上限',
                                    'data' => $value,
                                );
                                break;
                            case '7':
                                $errorJudge[] = array(
                                    'code' => 413,
                                    'message' => '分机类型错误',
                                    'data' => $value,
                                );
                                break;
                            default:
                                $errorJudge[] = array(
                                    'code' => 414,
                                    'message' => '格式错误',
                                    'data' => $value,
                                );
                                break;
                        }
                    }
                }
            }
        }
        //抛出最后的结果；
        if (empty($errorJudge)) {
            $ret = array(
                'code' => 200,
                'message' => 'ok',
            );

            return $ret;
        } else {
            $ret = array(
                'code' => 500,
                'message' => '错误',
                'errors' => array_merge($errorJudge, $successJudge),
            );

            return $ret;
        }
    }

    /**
     * 静态坐席签出
     *
     * @param array $param         签入参数，格式为
     *                             array(
     *                             vcc_id,//企业id
     *                             vcc_code,//企业代码
     *                             data = array(
     *                             array(
     *                             ag_num,//坐席工号
     *                             )
     *                             )
     *                             )
     *
     * @return array
     */
    public function staticAgentLogout(array $param = array())
    {
        /** @var  $user \Icsoc\SecurityBundle\Entity\CcCcods */
        //$user = $this->container->get("security.token_storage")->getToken()->getUser();
        if (empty($param)) {
            $ret = array(
                'code' => 415,
                'message' => '参数data不能为空',
            );

            return $ret;
        }

        $vccId = isset($param['vcc_id']) ? $param['vcc_id'] : 0;
        $vccCode = isset($param['vcc_code']) ? $param['vcc_code'] : '';
        $data = isset($param['data']) ? $param['data'] : array();
        if (empty($vccId) && empty($vccCode)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID和企业代码都为空',
            );

            return $ret;
        }

        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->container->get('doctrine.dbal.default_connection');
        if (empty($vccId) && !empty($vccCode)) {
            //根据vcc_code 查出vcc_id;
            $vccId = $conn->fetchColumn(
                " SELECT vcc_id FROM win_agent WHERE vcc_code = :vcc_code AND is_del=0 LIMIT 1 ",
                array('vcc_code' => $vccCode)
            );
        }
        if (!is_numeric($vccId)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符或企业代码不存在',
            );

            return $ret;
        }

        if (empty($data)) {
            $ret = array(
                'code' => 404,
                'message' => '参数中详细数据data为空',
            );

            return $ret;
        }
        if (!is_array($data)) {
            $ret = array(
                'code' => 405,
                'message' => '参数中详细数据data格式不对，要求为数组',
            );

            return $ret;
        }

        /** @var array $successJudge 存放正确结果判断的数组 */
        $successJudge = array();
        /** @var array $errorJudge 存放失败结果判断的数组 */
        $errorJudge = array();
        //$address = $this->container->getParameter('win_ip');
        $address = $this->container->get('icsoc_core.common.class')->newGetWinIp();
        //$address = $user->getWinIp();
        $port = $this->container->getParameter('win_socket_port');
        $logger = $this->container->get('logger');
        foreach ($data as $value) {
            if (!is_array($value)) {
                $errorJudge[] = array(
                    'code' => 405,
                    'message' => '参数中详细数据data格式不对，要求为数组',
                    'data' => $value,
                );
                continue;
            }
            if (!array_key_exists('ag_num', $value)) {
                $errorJudge[] = array(
                    'code' => 406,
                    'message' => '参数中详细数据data数组格式不对，必须包含工号ag_num',
                    'data' => $value,
                );
                continue;
            }
            //得出ag_id;
            $agId = $conn->fetchColumn(
                "SELECT id FROM win_agent WHERE ag_num = :ag_num AND vcc_id = :vcc_id AND is_del=0 LIMIT 1",
                array('ag_num' => $value['ag_num'], 'vcc_id' => $vccId)
            );
            $str = "aglogout(".$agId.")";
            $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
            if ($socket === false) {
                $errorCode = socket_last_error();
                $errorMsg = socket_strerror($errorCode);
                $logger->error('无法创建socket：【'.$errorCode.'】'.$errorMsg);
                $errorJudge[] = array(
                    'code' => 411,
                    'message' => '签出失败',
                    'data' => $value,
                );
                continue;
            }
            $res = @socket_connect($socket, $address, $port);
            //连接失败
            if ($res === false) {
                $errorCode = socket_last_error();
                $errorMsg = socket_strerror($errorCode);
                $logger->error('socket无法连接到【'.$address.':'.$port.'】：【'.$errorCode.'】'.$errorMsg);
                $errorJudge[] = array(
                    'code' => 411,
                    'message' => '签出失败',
                    'data' => $value,
                );
                continue;
            }
            $str .= "\r\n\r\n";
            $res = @socket_write($socket, $str, strlen($str));
            //发送数据失败
            if ($res === false) {
                $errorCode = socket_last_error();
                $errorMsg = socket_strerror($errorCode);
                $logger->error('socket发送数据失败：【'.$errorCode.'】'.$errorMsg);
                $errorJudge[] = array(
                    'code' => 411,
                    'message' => '签出失败',
                    'data' => $value,
                );
                continue;
            }
            $responce = @socket_read($socket, 100);
            if ($responce === false) {
                $errorCode = socket_last_error();
                $errorMsg = socket_strerror($errorCode);
                $logger->error('socket读取数据失败：【'.$errorCode.'】'.$errorMsg);
                $errorJudge[] = array(
                    'code' => 411,
                    'message' => '签出失败',
                    'data' => $value,
                );
                continue;
            }
            if (strstr($responce, 'Success')) {
                $successJudge[] = array(
                    'code' => 200,
                    'message' => 'ok',
                    'data' => $value,
                );
            } else {
                $responce = explode("\r\n", $responce);
                if (isset($responce[1])) {
                    $errcode = explode(":", $responce[1]);
                    switch (trim($errcode[1])) {
                        case '1':
                            $errorJudge[] = array(
                                'code' => 407,
                                'message' => '坐席不存在或坐席没有签入',
                                'data' => $value,
                            );
                            break;
                        case '2':
                            $errorJudge[] = array(
                                'code' => 408,
                                'message' => '不是静态坐席',
                                'data' => $value,
                            );
                            break;
                        case '3':
                            $errorJudge[] = array(
                                'code' => 409,
                                'message' => '坐席已从页面登录',
                                'data' => $value,
                            );
                            break;
                        default:
                            $errorJudge[] = array(
                                'code' => 410,
                                'message' => '格式错误',
                                'data' => $value,
                            );
                            break;
                    }
                }
            }
        }
        //抛出最后的结果
        if (empty($errorJudge)) {
            $ret = array(
                'code' => 200,
                'message' => 'ok',
            );

            return $ret;
        } else {
            $ret = array(
                'code' => 500,
                'message' => '错误',
                'errors' => array_merge($errorJudge, $successJudge),
            );

            return $ret;
        }
    }

    /**
     * 删除坐席
     *
     * @param array $param     参数，格式为
     *                         array(
     *                         vcc_id,//企业id
     *                         vcc_code,//企业代码？
     *                         ag_id = array(1,2,3)//坐席id
     *                         )
     *
     * @return array
     */
    public function deleteAgent(array $param = array())
    {
        $vccId = empty($param['vcc_id']) ? 0 : $param['vcc_id'];
        $vccCode = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $agIds = empty($param['ag_id']) ? array() : $param['ag_id'];

        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->container->get('doctrine.dbal.default_connection');
        if (empty($vccId)) {
            $msg = $vccId = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
            if (!empty($msg) && is_array($msg)) {
                return $msg;
            }
        } else {
            if (!is_numeric($vccId)) {
                $ret = array(
                    'code' => 402,
                    'message' => '企业ID包含非数字字符或企业代码不存在',
                );

                return $ret;
            }
            //判断企业ID 是否存在；
            $vccCode = $conn->fetchColumn(
                "SELECT vcc_code FROM cc_ccods WHERE status=1 AND vcc_id = :vcc_id",
                array('vcc_id' => $vccId)
            );
            if (empty($vccCode)) {
                $ret = array(
                    'code' => 403,
                    'message' => '企业ID不存在',
                );

                return $ret;
            }
        }
        if (empty($agIds)) {
            $ret = array(
                'code' => 403,
                'message' => '坐席ag_ids为空',
            );

            return $ret;
        }

        $errorMsg = array();

        $actionLogger = $this->container->get('icsoc_core.helper.logger');
        $conn->beginTransaction();
        $flag = true;
        foreach ($agIds as $agId) {
            if (!is_numeric($agId)) {
                $errorMsg[] = array(
                    'code' => 404,
                    'message' => '坐席ID包含非数字字符',
                    'ag_id' => $agId,
                );
                $flag = false;
                break;
            }
            //坐席登陆的不能删除
            $res = $conn->fetchAssoc(
                "SELECT ag_type,ag_sta
                FROM win_agent
                WHERE vcc_id = :vcc_id AND id = :ag_id",
                array('vcc_id' => $vccId, 'ag_id' => $agId)
            );
            if ($res['ag_type'] != 1 || $res['ag_sta'] != 0) {
                $errorMsg[] = array(
                    'code' => 406,
                    'message' => '坐席在登录状态',
                    'ag_id' => $agId,
                );
                $flag = false;
                break;
            }

            $num = $conn->update('win_agent', array('is_del' => 1), array('vcc_id' => $vccId, 'id' => $agId));
            if ($num > 0) {
                //删除掉 win_agqu;
                $conn->delete('win_agqu', array('ag_id' => $agId));
                $errorMsg[] = array(
                    'code' => 200,
                    'message' => 'ok',
                    'ag_id' => $agId,
                );
                //删除对应监控配置信息
                $conn->delete("cc_monitor_config", array('vcc_id' => $vccId, 'user_id' => $agId));
            } else {
                $errorMsg[] = array(
                    'code' => 405,
                    'message' => '删除失败',
                    'ag_id' => $agId,
                );
                $flag = false;
                break;
            }
        }
        //如果有删除失败的项，rollback所有数据
        if ($flag == false) {
            $conn->rollBack();
        } else {
            $conn->commit();
            foreach ($agIds as $agId) {
                //发送到消息队列
                $this->writeMq(array('action' => 'delete', 'data' => array('vcc_id' => $vccId, 'ag_id' => $agId)));
                //记录日志
                $logStr = $this->container->get('translator')->trans('Delete agent %str%', array('%str%' => $agId));
                $actionLogger->actionLog(ActionLogger::ACTION_DELETE, $logStr);
            }
        }

        return array(
            'code' => 500,
            'message' => '结果',
            'data' => $errorMsg,
        );
    }

    /**
     * 编辑坐席接口
     *
     * @param array $param     参数，格式为
     *                         array(
     *                         vcc_id,//企业id
     *                         vcc_code,//企业代码？
     *                         ag_id,//坐席id
     *                         ag_name,//坐席名称
     *                         ag_password,//坐席密码
     *                         ag_role,//坐席前台角色
     *                         user_role,//坐席角色
     *                         )
     *
     * @return array
     */
    public function editAgent(array $param = array())
    {
        $conn = $this->container->get('doctrine.dbal.default_connection');
        $vccId = empty($param['vcc_id']) ? 0 : $param['vcc_id'];
        $vccCode = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $agId = empty($param['ag_id']) ? 0 : $param['ag_id'];
        $agName = empty($param['ag_name']) ? '' : $param['ag_name'];
        $agNickname = empty($param['ag_nickname']) ? '' : $param['ag_nickname'];
        $agPassword = empty($param['ag_password']) ? '' : $param['ag_password'];
        $agRole = !isset($param['ag_role']) ? false : $param['ag_role'];
        $userRole = !isset($param['user_role']) ? false : $param['user_role'];
        $crmDatarole = !isset($param['crm_datarole']) ? false : $param['crm_datarole']; //crm数据权限
        $groupId = empty($param['group_id']) ? '0' : $param['group_id']; //业务组
        $belongQueues = !isset($param['belong_queues']) ? false : $param['belong_queues']; //所属技能组，分配
        $agStatus = !isset($param['ag_status']) ? 1 : $param['ag_status'];
        //$user_queues = empty($param['user_queues']) ? '' : implode(',', $param['user_queues']); //管理技能组
        //$user_type = empty($param['user_type']) ? 0 : $param['user_type']; //后台数据权限
        if (empty($vccId)) {
            $msg = $vccId = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
            if (!empty($msg) && is_array($msg)) {
                return $msg;
            }
        } else {
            if (!is_numeric($vccId)) {
                $ret = array(
                    'code' => 402,
                    'message' => '企业ID包含非数字字符或企业代码不存在',
                );

                return $ret;
            }
            //判断企业ID 是否存在；
            $vccCode = $conn->fetchColumn(
                "SELECT vcc_code FROM cc_ccods WHERE status=1 AND vcc_id = :vcc_id",
                array('vcc_id' => $vccId)
            );
            if (empty($vccCode)) {
                $ret = array(
                    'code' => 403,
                    'message' => '企业ID不存在',
                );

                return $ret;
            }
        }
        if (empty($agId)) {
            $ret = array(
                'code' => 403,
                'message' => '坐席ID为空',
            );

            return $ret;
        }

        if (!is_numeric($agId)) {
            $ret = array(
                'code' => 404,
                'message' => '坐席ID包含非数字字符',
            );

            return $ret;
        }

//        if (empty($ag_name)) {
//            $ret = array(
//                'code' => 405,
//                'message' => '坐席名称为空',
//            );
//
//            return $ret;
//        }

        //前台坐席类型 406
        if ($agRole !== false && !in_array($agRole, $this->agRoles)) {
            $ret = array(
                'code' => 406,
                'message' => '坐席类型不正确',
            );

            return $ret;
        }

        //407 坐席角色是否属于该企业
        if (!empty($userRole)) {
            $result = $this->container->get('icsoc_data.validator')->checkIfRoleBelongsToVcc($vccId, $userRole);
            if ($result === false) {
                $ret = array(
                    'code' => 407,
                    'message' => '角色不属于该企业',
                );

                return $ret;
            }

            /** @var array $roleInfo 角色信息 */
            $roleInfo = $this->container->get('icsoc_data.model.role')
                ->getRoleInfo(array('vcc_code' => $vccCode, 'role_id' => $userRole));

            $code = isset($roleInfo['code']) ? $roleInfo['code'] : '';
            $message = isset($roleInfo['message']) ? $roleInfo['message'] : '';
            $data = isset($roleInfo['data']) ? $roleInfo['data'] : array();
            if ($code != 200) {
                return array(
                    'code' => 419,
                    'message' => $message,
                );
            }
        }

        //马蜂窝特殊处理
//        if ($vccId == '2000135') {
//            $userQueues = empty($param['user_queues']) ? '' : implode(',', $param['user_queues']); //管理技能组
//            $userType = empty($param['user_type']) ? 0 : $param['user_type']; //后台数据权限
//        } else {
//            $userType = isset($data['user_type']) ? $data['user_type'] : 0;
//            $userQueues = isset($data['user_queues']) ? $data['user_queues'] : '';
//        }
        $userType = isset($data['user_type']) ? $data['user_type'] : 0;
        $userQueues = isset($data['user_queues']) ? $data['user_queues'] : '';
        $data = array();
        $select = '1';
        if (!empty($agName)) {
            $data['ag_name'] = $agName;
            $select .= ',ag_name';
        }
        if (!empty($agNickname)) {
            $data['ag_nickname'] = $agNickname;
            $select .= ',ag_nickname';
        }
        if ($agRole !== false) {
            $data['ag_role'] = $agRole;
            $select .= ',ag_role';
        }

        if ($crmDatarole !== false) {
            $data['crm_datarole'] = $crmDatarole;
            $select .= ',crm_datarole';
        }
        if (!empty($userRole)) {
            $data['user_role'] = $userRole;
            $data['user_type'] = $userType;
            $data['user_queues'] = $userQueues;
            $select .= ',user_role,user_type,user_queues';
//        } elseif ($vccId == '2000135') {
////            $data['user_type'] = $userType;
////            $data['user_queues'] = $userQueues;
////            $select .= ',user_type,user_queues';
        }
        if (!empty($groupId)) {
            $data['group_id'] = $groupId;
            $select .= ',group_id';
        }
        if (!empty($agStatus)) {
            $data['ag_status'] = $agStatus;
            $select .= ',ag_status';
        }
        //没有东西需要修改；
        if (empty($data)) {
            return array(
                'code' => 200,
                'message' => 'ok',
            );
        }

        //先查出原值；记录日志差别；
        $oldAgent = $conn->fetchAssoc(
            "SELECT {$select} FROM win_agent WHERE id = :id ",
            array('id' => $agId)
        );
        //还得验证是否超标
        $isOver = $this->agentIsOverproof($vccId); //获得坐席总数;
        if ($isOver < 0 || ($agRole !== false && $data['ag_role'] != -1 && $oldAgent['ag_role'] == -1 && $isOver == 0)) {
            return array("code" => 409, "message" => '坐席数量已经超标');
        }
        $logStr = '';

        $diff = array_diff_assoc($data, $oldAgent);
        foreach ($diff as $k => $v) {
            $logStr .= "[".$k."]:".$oldAgent[$k]."=>".$data[$k]." ";
        }
        if (!empty($agPassword)) {
            $data = array_merge($data, array('ag_password' => $agPassword));
        }
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn->update('win_agent', $data, array('vcc_id' => $vccId, 'id' => $agId));
        $data['vcc_id'] = $vccId;
        $data['ag_id'] = $agId;
        $this->writeMq(array('action' => 'update', 'data' => $data));
        if (is_array($belongQueues)) {
            //先删除入；在插入
            $conn->beginTransaction();
            try {
                $conn->executeQuery("DELETE FROM win_agqu WHERE ag_id = :ag_id", array('ag_id' => $agId));
                foreach ($belongQueues as $que) {
                    $msgQueId = $this->container->get('icsoc_data.validator')->vccQue($vccId, $que, 403);
                    if (!empty($msgQueId)) {
                        $conn->rollBack();

                        return array(
                            'code' => 420,
                            'message' => '技能组不存在',
                        );
                    }
                    $conn->insert("win_agqu", array('ag_id' => $agId, 'que_id' => $que, 'skill' => 1));
                }
                $conn->commit();
                $address = $this->container->get('icsoc_core.common.class')->newGetWinIp();
                $port = $this->container->getParameter('win_socket_port');
                $this->container->get('icsoc_data.validator')->reloadAgent($vccId, $address, $agId, $port);
            } catch (Exception $e) {
                $conn->rollBack();
            }
        }
        $ret = array(
            'code' => 200,
            'message' => 'ok',
        );

        if (!empty($logStr)) {
            $content = $this->container->get("translator")->trans("Update agent %str%", array('%str%' => $logStr));
            $this->container->get("icsoc_core.helper.logger")->actionLog(ActionLogger::ACTION_UPDATE, $content);
        }

        return $ret;
    }

    /**
     * 添加坐席
     *
     * @param array $param     参数，格式为
     *                         array(
     *                         vcc_id,//企业id
     *                         vcc_code,//企业代码？
     *                         belong_queues,//所属技能组 array 分配
     *                         ag_num,//坐席工号
     *                         ag_name,//坐席名称
     *                         ag_password,//坐席密码
     *                         ag_role,//坐席前台角色
     *                         user_role,//坐席角色
     *                         )
     *
     * @return array
     */
    public function addAgent(array $param = array())
    {
        $vccId = empty($param['vcc_id']) ? 0 : $param['vcc_id'];
        $vccCode = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        // $que_id = empty($param['que_id']) ? 0 : $param['que_id'];
        $agNum = empty($param['ag_num']) ? '' : $param['ag_num'];
        $agName = empty($param['ag_name']) ? '' : $param['ag_name'];
        $agNickname = empty($param['ag_nickname']) ? '' : $param['ag_nickname'];
        $agPassword = empty($param['ag_password']) ? '' : $param['ag_password'];
        $agRole = empty($param['ag_role']) ? '' : $param['ag_role'];
        $userRole = empty($param['user_role']) ? '' : $param['user_role'];
        $crmDatarole = empty($param['crm_datarole']) ? '' : $param['crm_datarole']; //crm数据权限
        $groupId = empty($param['group_id']) ? '' : $param['group_id']; //业务组
        $belongQueues = empty($param['belong_queues']) ? array() : $param['belong_queues']; //所属技能组，分配
        $agStatus = empty($param['ag_status']) ? 1 : $param['ag_status'];
        //$user_queues = empty($param['user_queues']) ? '' : implode(',', $param['user_queues']); //管理技能组
        //$user_type = empty($param['user_type']) ? 0 : $param['user_type']; //后台数据权限
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->container->get("doctrine.dbal.default_connection");
        if (empty($vccId)) {
            $msg = $vccId = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
            if (!empty($msg) && is_array($msg)) {
                return $msg;
            }
        } else {
            if (!is_numeric($vccId)) {
                $ret = array(
                    'code' => 402,
                    'message' => '企业ID包含非数字字符',
                );

                return $ret;
            }
            //判断企业ID 是否存在；
            $vccCode = $conn->fetchColumn(
                "SELECT vcc_code FROM cc_ccods WHERE status=1 AND vcc_id=:vcc_id",
                array('vcc_id' => $vccId)
            );
            if (empty($vccCode)) {
                $ret = array(
                    'code' => 403,
                    'message' => '企业ID不存在',
                );

                return $ret;
            }
        }
        //判断技能组ID,貌似没有用了
        if (!empty($queId)) {
            if (!is_numeric($queId)) {
                $ret = array(
                    'code' => 405,
                    'message' => '技能组ID包含非数字字符',
                );

                return $ret;
            }
            $queIfExits = $conn->fetchColumn(
                "SELECT id FROM win_queue WHERE vcc_id=:vcc_id AND id=:que_id AND is_del=0",
                array('vcc_id' => $vccId, 'que_id' => $queId)
            );
            if (!$queIfExits) {
                $ret = array(
                    'code' => 406,
                    'message' => '技能组ID不存在',
                );

                return $ret;
            }
        }
        //在判断ag_num
        if (empty($agNum)) {
            $ret = array(
                'code' => 407,
                'message' => '坐席工号为空',
            );

            return $ret;
        }

        //判断坐席工号是否已经存在
        $agNumIfExists = $conn->fetchColumn(
            "SELECT id FROM win_agent WHERE vcc_id = :vcc_id AND is_del = 0 AND ag_num = :ag_num",
            array('vcc_id' => $vccId, 'ag_num' => $agNum)
        );
        if ($agNumIfExists) {
            $ret = array(
                'code' => 409,
                'message' => '坐席工号已经存在',
            );

            return $ret;
        }

        //坐席名称 非必须
//        if (empty($ag_name)) {
//            $ret = array(
//                'code' => 410,
//                'message' => '坐席名称为空',
//            );
//
//            return $ret;
//        }
        //坐席密码
        if (empty($agPassword)) {
            $ret = array(
                'code' => 411,
                'message' => '坐席密码为空',
            );

            return $ret;
        }

        //前台坐席类型
        if (!in_array($agRole, $this->agRoles)) {
            $ret = array(
                'code' => 412,
                'message' => '坐席类型不正确',
            );

            return $ret;
        }

        //坐席角色是否属于该企业
        if (!empty($userRole)) {
            $result = $this->container->get('icsoc_data.validator')->checkIfRoleBelongsToVcc($vccId, $userRole);
            if ($result === false) {
                $ret = array(
                    'code' => 413,
                    'message' => '角色不属于该企业',
                );

                return $ret;
            }
        }

        //查看最大坐席数
        $agents = $conn->fetchColumn(
            "SELECT agents
            FROM cc_ccods
            WHERE vcc_id = :vcc_id ",
            array('vcc_id' => $vccId)
        );

        $alreay = $conn->fetchColumn(
            "SELECT count(*)
            FROM win_agent
            WHERE vcc_id = :vcc_id AND ag_role <> -1 AND is_del = 0",
            array('vcc_id' => $vccId)
        );

        if ($alreay >= $agents && $agRole != -1) {
            $ret = array(
                'code' => 415,
                'message' => '坐席已经数量达到极限',
            );

            return $ret;
        }

        /** @var array $roleInfo 角色信息 */
        $roleInfo = $this->container->get('icsoc_data.model.role')
            ->getRoleInfo(array('vcc_code' => $vccCode, 'role_id' => $userRole));

        $code = isset($roleInfo['code']) ? $roleInfo['code'] : '';
        $message = isset($roleInfo['message']) ? $roleInfo['message'] : '';
        $data = isset($roleInfo['data']) ? $roleInfo['data'] : array();
        if ($code != 200) {
            return array(
                'code' => 419,
                'message' => $message,
            );
        }
//        //马蜂窝特殊处理
//        if ($vccId == '2000135') {
//            $userQueues = empty($param['user_queues']) ? '' : implode(',', $param['user_queues']); //管理技能组
//            $userType = empty($param['user_type']) ? 0 : $param['user_type']; //后台数据权限
//        } else {
//            $userType = isset($data['user_type']) ? $data['user_type'] : 0;
//            $userQueues = isset($data['user_queues']) ? $data['user_queues'] : '';
//        }
        $userType = isset($data['user_type']) ? $data['user_type'] : 0;
        $userQueues = isset($data['user_queues']) ? $data['user_queues'] : '';
        $conn->beginTransaction();
        try {
            $data = array(
                'vcc_id' => $vccId,
                'vcc_code' => $vccCode,
                'ag_num' => $agNum,
                'ag_password' => $agPassword,
                'ag_name' => $agName,
                'ag_nickname' => $agNickname,
                'user_role' => $userRole,
                'ag_role' => $agRole,
                'crm_datarole' => $crmDatarole,
                'user_queues' => $userQueues,
                'user_type' => $userType,
                'group_id' => $groupId,
                'ag_status' => $agStatus,
            );
            $conn->insert('win_agent', $data);
            $agId = $conn->lastInsertId();
            $content = $this->container->get('translator')->trans("Add agent %agNum%", array('%agNum%' => $agNum));
            $this->container->get("icsoc_core.helper.logger")->actionLog(ActionLogger::ACTION_ADD, $content);
            //分配到技能组
            if (!empty($belongQueues) && is_array($belongQueues)) {
                $errorMsg = array();
                foreach ($belongQueues as $queId) {
                    $msgQueId = $this->container->get('icsoc_data.validator')->vccQue($vccId, $queId, 403);
                    if (!empty($msgQueId)) {
                        $errorMsg = array(
                            'code' => 420,
                            'message' => '技能组不存在',
                        );
                        break;
                    }
                    //再判断该坐席是否分配了
                    $total = $conn->fetchColumn(
                        'SELECT count(*) FROM win_agqu WHERE que_id = :que_id AND ag_id = :ag_id ',
                        array('que_id' => $queId, 'ag_id' => $agId)
                    );
                    if ($total) {
                        $errorMsg = array(
                            'code' => 421,
                            'message' => '坐席已经被分配到此技能组',
                        );
                        break;
                    }
                    $conn->insert('win_agqu', array('que_id' => $queId, 'ag_id' => $agId, 'skill' => 1));
                }
            }
            if (!empty($errorMsg)) {
                $conn->rollBack();

                return $errorMsg;
            }
            $conn->commit();

            //向队列添加操作信息
            $data['ag_id'] = $agId;
            $this->writeMq(array('action' => 'create', 'data' => $data));
            //添加完成之后，重载坐席
            $address = $this->container->get('icsoc_core.common.class')->newGetWinIp();
            $port = $this->container->getParameter('win_socket_port');
            $this->container->get('icsoc_data.validator')->reloadAgent($vccId, $address, $agId, $port);

            $ret = array(
                'code' => 200,
                'lastId' => $agId,
                'message' => 'ok',
            );

            return $ret;
        } catch (Exception $e) {
            $conn->rollBack();
            $ret = array(
                'code' => 414,
                'message' => '添加坐席失败['.$e->getMessage().']',
            );

            return $ret;
        }

    }

    /**
     * 获取企业下的坐席信息
     *
     * @param array $param     参数，格式为
     *                         array(
     *                         vcc_id,//企业id
     *                         vcc_code,//企业代码？
     *                         que_id,//技能组id
     *                         ag_num,//坐席工号
     *                         ag_name,//坐席名称
     *                         ag_password,//坐席密码
     *                         ag_role,//坐席前台角色
     *                         user_role,//坐席角色
     *                         )
     *
     * @return array
     */
    public function listAgent(array $param = array())
    {
        $vccCode = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $agId = empty($param['ag_id']) ? 0 : $param['ag_id'];
        $queId = empty($param['que_id']) ? 0 : (int) $param['que_id'];
        $groupId = empty($param['group_id']) ? 0 : (int) $param['group_id'];
        $infos = empty($param['info']) ? '' : $this->purifyHtml($param['info']);

        //分页搜索相关信息；
        $info = array();
        if (!empty($infos)) {
            $info = json_decode($infos, true);
            if (json_last_error()) {
                return array('code' => 404, 'message' => 'info格式非json');
            }
        }

        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->container->get("doctrine.dbal.default_connection");

        /** @var array $msg 验证vcc_code是否正确 */
        $msg = $vccId = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        if (!empty($agId)) {
            if (!is_numeric($agId)) {
                $ret = array(
                    'code' => 403,
                    'message' => '坐席ID包含非数字字符',
                );

                return $ret;
            }
        }

        //处理搜索和排序条件
        $where = '';
        if (isset($info['filter'])) {
            if (isset($info['filter']['keyword']) && !empty($info['filter']['keyword'])) {
                $keyword = $info['filter']['keyword'];
                if (strpos($keyword, ',')) {
                    $keywords = explode(",", $keyword);
                    $keywords = array_unique($keywords);
                    $agStr = $phoStr = $nameStr = '';
                    $i = 1;
                    $count = count($keywords);
                    foreach ($keywords as $word) {
                        $agStr .= " ag_num Like '%".$word."%' OR ";
                        $phoStr .= " (pho_num Like '%".$word."%' AND ag_type = 2) OR ";
                        $nameStr .= " ag_name Like '%".$word."%' ".(($i == $count) ? '' : ' OR ');
                        $i++;
                    }
                    $where .= ' AND ('.$agStr.$phoStr.$nameStr.')';
                } else {
                    $where .= " AND (ag_num  LIKE '%".$keyword."%'
                     OR  (pho_num Like '%".$keyword."%' AND ag_type = 2) OR ag_name LIKE '%".$keyword."%') ";
                }
            }
            if (isset($info['filter']['assign_keyword']) && !empty($info['filter']['assign_keyword'])) {
                $assignKeyword = $info['filter']['assign_keyword']; //区分列表和分配的搜索；
                $where .= " AND (ag_num  LIKE '%".$assignKeyword."%' OR ag_name LIKE '%".$assignKeyword."%') ";
            }
            if (isset($info['filter']['id']) && $info['filter']['id'] !== false) {
                $where .= " AND a.id IN (".$info['filter']['id'].")";
            }
            if (isset($info['filter']['user_role']) && !empty($info['filter']['user_role']) && $info['filter']['user_role'] != 'all') {
                $where .= " AND a.user_role IN (".$info['filter']['user_role'].")";
            }
            if (isset($info['filter']['notid']) && $info['filter']['notid'] !== false) {
                $where .= " AND a.id NOT IN (".$info['filter']['notid'].")";
            }
        }
        $where .= !empty($agId) ? " AND a.id = :ag_id " : '';
        $where .= !empty($queId) ? ' AND ag.que_id = :que_id ' : '';
        $where .= !empty($groupId) ? ' AND a.group_id = :group_id ' : '';
        $params = !empty($agId) ? array('vcc_id' => $vccId, 'ag_id' => $agId) : array('vcc_id' => $vccId);
        $params = !empty($queId) ? array_merge($params, array('que_id' => $queId)) : $params;
        $groupIdValue = $groupId == -1 ? 0 : $groupId;
        $params = !empty($groupId) ? array_merge($params, array('group_id' => $groupIdValue)) : $params;
        $joinTable = $skill = '';
        if (!empty($queId)) {
            $joinTable = ' LEFT JOIN win_agqu as ag ON ag.ag_id = a.id ';
            $skill = ',ag.skill,ag.id as aqid ';
        }
        //查出总计的条数t;
        $count = $conn->fetchColumn(
            "SELECT count(*)
            FROM win_agent as a  {$joinTable}
            WHERE a.vcc_id = :vcc_id AND a.is_del = 0 ".$where,
            $params
        );
        $limit = isset($info['pagination']['rows']) ? $info['pagination']['rows'] : 1000;
        $totalPages = ceil($count / $limit);
        $page = isset($info['pagination']['page']) && $info['pagination']['page'] > 1 ? $info['pagination']['page'] : 1;
        $page = $page > $totalPages ? $totalPages : $page;
        $start = $limit * $page - $limit;
        $start = $start > 0 ? $start : 0;
        $flag = false;
        if (isset($info['sort']['field'])) {
            //就需要验证传入字段是否属于坐席表
            $flag = $this->container->get('icsoc_data.helper')->fieldExistTable($info['sort']['field'], 'win_agent');
        }
        $sort = $flag ? $info['sort']['field'] : 'id';
        $order = isset($info['sort']['order']) && in_array(strtolower($info['sort']['order']), array('desc', 'asc'))
            ? $info['sort']['order'] : 'desc';
        //开始查询
        $sql = "SELECT a.id as ag_id,a.vcc_id,a.ag_num,a.ag_name,a.ag_nickname,a.ag_password,a.ag_role,a.group_id,a.user_type,
            a.crm_datarole,a.user_role,r.name as role_name,a.ag_type,a.pho_num,a.ag_status  {$skill}
            FROM win_agent as a
            LEFT JOIN cc_roles as r
            ON a.user_role = r.role_id  {$joinTable}
            WHERE a.vcc_id = :vcc_id AND a.is_del = 0 ";
        $sql .= $where."  ORDER BY a.$sort $order LIMIT $start,$limit";
        $data = $conn->fetchAll($sql, $params);
        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'total' => $count,
            'page' => $page,
            'totalPage' => $totalPages,
            'data' => $data,
        );

        return $ret;
    }

    /**
     * 修改坐席密码
     *
     * @param array $param     参数，格式为
     *                         array(
     *                         vcc_id,//企业id
     *                         vcc_code,//企业代码？
     *                         ag_id,//坐席id
     *                         old_password,//原始密码
     *                         new_password,//新密码
     *                         )
     *
     * @return array
     */
    public function updateAgentPassword(array $param = array())
    {
        $vccCode = empty($param['vcc_code']) ? 0 : $param['vcc_code'];
        $agId = empty($param['ag_id']) ? 0 : $param['ag_id'];
        $oldPassword = empty($param['old_password']) ? '' : $param['old_password'];
        $newPassword = empty($param['new_password']) ? '' : $param['new_password'];

        /** @var array $msg 验证vcc_code是否正确 */
        $msg = $vccId = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        if (empty($agId)) {
            $ret = array(
                'code' => 403,
                'message' => '坐席ID为空',
            );

            return $ret;
        }

        if (!is_numeric($agId)) {
            $ret = array(
                'code' => 404,
                'message' => '坐席ID包含非数字字符',
            );

            return $ret;
        }

        if (empty($oldPassword)) {
            $ret = array(
                'code' => 405,
                'message' => '旧密码为空',
            );

            return $ret;
        }

        //新密码为空
        if (empty($newPassword)) {
            $ret = array(
                'code' => 407,
                'message' => '新密码为空',
            );

            return $ret;
        }

        if ($oldPassword == $newPassword) {
            $ret = array(
                'code' => 409,
                'message' => '新密码和原始密码一样，无需修改',
            );

            return $ret;
        }

        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->container->get("doctrine.dbal.default_connection");
        //验证旧密码是否正确
        $password = $conn->fetchColumn(
            "SELECT ag_password FROM win_agent WHERE id=:ag_id AND vcc_id=:vcc_id LIMIT 1",
            array('vcc_id' => $vccId, 'ag_id' => $agId)
        );
        if ($password != $oldPassword) {
            $ret = array(
                'code' => 406,
                'message' => '旧密码错误',
            );

            return $ret;
        }

        try {
            $conn->update(
                "win_agent",
                array('ag_password' => $newPassword),
                array('vcc_id' => $vccId, 'id' => $agId)
            );
            $ret = array(
                'code' => 200,
                'message' => 'ok',
            );

            return $ret;
        } catch (Exception $e) {
            $ret = array(
                'code' => 408,
                'message' => '修改失败['.$e->getMessage().']',
            );

            return $ret;
        }
    }

    /**
     * 坐席登录
     *
     * @param array $param     参数，格式为
     *                         array(
     *                         vcc_code,//企业代码
     *                         ag_num,//坐席工号
     *                         password,//密码
     *                         )
     *
     * @return array
     */
    public function signin(array $param = array())
    {
        $vccCode = empty($param['vcc_code']) ? '' : $param['vcc_code'];
        $agNum = empty($param['ag_num']) ? '' : $param['ag_num'];
        $password = empty($param['password']) ? '' : $param['password'];

        /** @var array $msg 验证vcc_code是否正确 */
        $msg = $vccId = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        if (empty($agNum)) {
            $ret = array(
                'code' => 403,
                'message' => '坐席工号为空',
            );

            return $ret;
        }
        if (empty($password)) {
            $ret = array(
                'code' => 404,
                'message' => '密码为空',
            );

            return $ret;
        }

        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->container->get("doctrine.dbal.default_connection");
        $result = $conn->fetchAssoc(
            "SELECT wa.id AS ag_id,cc.vcc_id,cc.db_main_ip,cc.db_slave_ip,cc.db_name,
            cc.db_user,cc.db_password,cc.role_action,wa.group_id,wg.group_name,
            cc.system_version,ccs.tel_addr,ccs.tel_port,ccs.addr_flash,ccs.addr_websocket
            FROM win_agent as wa
            LEFT JOIN cc_ccods AS cc
            ON cc.vcc_id = wa.vcc_id
            LEFT JOIN win_group AS wg
            ON wa.group_id = wg.group_id
            LEFT JOIN cc_cti_servers AS ccs
            ON cc.telid=ccs.telid
            WHERE wa.vcc_code=:vcc_code AND wa.ag_num=:ag_num
            AND wa.ag_password=:password AND wa.is_del=0",
            array('vcc_code' => $vccCode, 'ag_num' => $agNum, 'password' => $password)
        );

        if (empty($result)) {
            $ret = array(
                'code' => 405,
                'message' => '验证失败,没有匹配到相应数据',
            );

            return $ret;
        } else {
            $ret = array(
                'code' => 200,
                'message' => 'ok',
                'data' => $result,
            );

            return $ret;
        }
    }

    /**
     * 获取当前空闲坐席
     *
     * @param array $param     参数，格式为
     *                         array(
     *                         vcc_id,//企业id
     *                         )
     *
     * @return array
     */
    public function getFreeAgent(array $param = array())
    {
        $vccId = empty($param['vcc_id']) ? 0 : $param['vcc_id'];

        if (empty($vccId)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID为空',
            );

            return $ret;
        }

        if (!is_numeric($vccId)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符',
            );

            return $ret;
        }

        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->container->get("doctrine.dbal.default_connection");
        $list = $conn->fetchAll(
            "SELECT ag_id,pho_num,ag_name,ag_num FROM win_agmonitor WHERE ag_sta=1 AND vcc_id=:vcc_id",
            array('vcc_id' => $vccId)
        );

        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'data' => $list,
        );

        return $ret;
    }

    /**
     * 签出+签入 所有登录的静态坐席
     *
     * @param array $param     参数，格式为
     *                         array(
     *                         vcc_id,//企业id
     *                         )
     *
     * @return array
     */
    public function getReadyAgent(array $param = array())
    {
        $vccId = empty($param['vcc_id']) ? 0 : $param['vcc_id'];

        if (empty($vccId)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID为空',
            );

            return $ret;
        }

        if (!is_numeric($vccId)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符',
            );

            return $ret;
        }
        $user = $this->container->get('security.token_storage')->getToken()->getUser();
        $flag = $user->getFlag();
        if ($flag != 'ccadmin' && $flag != 'ccod') {
            $ret = array(
                'code' => 403,
                'message' => '没有管理员权限',
            );

            return $ret;
        }
        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->container->get("doctrine.dbal.default_connection");
        $list = $conn->fetchAll(
            "SELECT a.id as agid,a.vcc_id as vccid,a.ag_num as agnum,a.ag_name as agname,a.group_id as agroupid,getagqu(a.id) as queinfo,
             b.pho_num as phonum,b.id as phoid,b.pho_type as photype,b.pho_chan photrink,b.pho_pass phopass,a.ag_owncaller as agowncaller,
             a.tellevel as agtellevel
             FROM win_agent a LEFT JOIN win_phone b on a.vcc_id=b.vcc_id
             AND a.pho_id=b.id WHERE  a.is_del=0 AND a.ag_type in (2,4) AND a.vcc_id=:vcc_id",
            array('vcc_id' => $vccId)
        );
        if (empty($list)) {
            $ret = array(
                'code' => 404,
                'message' => '没有登录的坐席',
            );

            return $ret;
        }
        $address = $this->container->get('icsoc_core.common.class')->newGetWinIp();
        $port = $this->container->getParameter('win_socket_port');
        foreach ($list as $val) {
            //先签出
            $str = "aglogout(".$val['agid'].")";
            $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
            @socket_connect($socket, $address, $port);
            $str .= "\r\n\r\n";
            @socket_write($socket, $str, strlen($str));
            //再签入
            $locationArr = $this->container->get("icsoc_data.model.location")->getNumberloc($val['phonum']);
            $agquInfo = explode(',', rtrim($val['queinfo'], ","));
            $queInfo = array();
            foreach ($agquInfo as $vl) {
                $queArray = explode('-', $vl);
                foreach ($queArray as $queKey => $queValue) {
                    $queArray[$queKey] = intval($queValue);
                }
                $queInfo[] = $queArray;
            }
            $arr = array(
                'cli' => "aglogin",
                'ret' => 0,
                'vccid' => intval($val['vccid']),
                'agid' => intval($val['agid']),
                'agnum' => $val['agnum'],
                'agname' => $val['agname'],
                'phoid' => intval($val['phoid']),
                'photype' => intval($val['photype']),
                'phonum' => $val['phonum'],
                'photrunk' => $val['photrink'],
                'phopass' => $val['phopass'],
                'queinfo' => $queInfo,
                'owncaller' => $val['agowncaller'],
                'tellevel' => intval($val['agtellevel']),
                'gid' => intval($val['agroupid']),
                'pho_acode' => $locationArr['data']['code'],
                'pho_aname' => $locationArr['data']['city'],
                'pho_type' => $locationArr['data']['type'],
                'pho_vendor' => "",
                'pho_proxy' => "",
            );
            $str = json_encode($arr);
            $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
            @socket_connect($socket, $address, $port);
            $str .= "\r\n\r\n";
            @socket_write($socket, $str, strlen($str));
        }

        $ret = array(
            'code' => 200,
            'message' => 'ok',
        );

        return $ret;
    }

    /**
     * 获取当前通话中的坐席
     *
     * @param array $param     参数，格式为
     *                         array(
     *                         vcc_id,//企业id
     *                         )
     *
     * @return array
     */
    public function getOnlineAgent(array $param = array())
    {
        $vccId = empty($param['vcc_id']) ? 0 : $param['vcc_id'];

        if (empty($vccId)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID为空',
            );

            return $ret;
        }

        if (!is_numeric($vccId)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符',
            );

            return $ret;
        }

        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->container->get("doctrine.dbal.default_connection");
        $list = $conn->fetchAll(
            "SELECT ag_id,pho_num,sec_to_time(unix_timestamp()-pho_sta_time)AS ag_time FROM win_agmonitor
             WHERE pho_sta=2 AND vcc_id=:vcc_id",
            array('vcc_id' => $vccId)
        );

        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'data' => $list,
        );

        return $ret;
    }

    /**
     * 设置坐席转接电话
     *
     * @param array $param     参数，格式为
     *                         array(
     *                         vcc_id,//企业id
     *                         vcc_code,//企业代码？
     *                         ag_id,//坐席id
     *                         old_password,//原始密码
     *                         new_password,//新密码
     *                         )
     *
     * @return array
     *
     */
    public function setAgentTransferPhone(array $param = array())
    {
        $vccId = empty($param['vcc_id']) ? 0 : $param['vcc_id'];
        $agId = empty($param['ag_id']) ? 0 : $param['ag_id'];
        $phone = empty($param['phone']) ? '' : $param['phone'];
        $state = empty($param['state']) ? 1 : $param['state'];

        if (empty($vccId)) {
            $ret = array(
                'code' => 401,
                'message' => '企业ID为空',
            );

            return $ret;
        }

        if (!is_numeric($vccId)) {
            $ret = array(
                'code' => 402,
                'message' => '企业ID包含非数字字符',
            );

            return $ret;
        }

        if (empty($agId)) {
            $ret = array(
                'code' => 403,
                'message' => '坐席ID为空',
            );

            return $ret;
        }

        if (!is_numeric($agId)) {
            $ret = array(
                'code' => 404,
                'message' => '坐席ID包含非数字字符',
            );

            return $ret;
        }

        if (empty($phone)) {
            $ret = array(
                'code' => 405,
                'message' => '手机号为空',
            );

            return $ret;
        }

        if (!is_numeric($phone)) {
            $ret = array(
                'code' => 406,
                'message' => '手机号码含非数字字符',
            );

            return $ret;
        }

        if (strlen($phone) != 11) {
            $ret = array(
                'code' => 407,
                'message' => '手机号码不是11位',
            );

            return $ret;
        }

        if (!in_array($state, array(1, 0))) {
            $ret = array(
                'code' => 408,
                'message' => '状态值不是0或1',
            );

            return $ret;
        }

        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->container->get("doctrine.dbal.default_connection");
        //判断ag_id 是否存在
        $agent = $conn->fetchAssoc(
            "SELECT id FROM win_agent WHERE is_del=0 AND vcc_id=:vcc_id AND id=:ag_id",
            array('vcc_id' => $vccId, 'ag_id' => $agId)
        );

        if (empty($agent)) {
            $ret = array(
                'code' => 409,
                'message' => '对应的坐席不存在',
            );

            return $ret;
        }

        $res = $conn->exec(
            "INSERT INTO win_agextphone(vcc_id,ag_id,pho_num,state)
            VALUES('{$vccId}','{$agId}','{$phone}','{$state}')
            ON DUPLICATE KEY UPDATE pho_num='{$phone}',state='{$state}'"
        );
        if ($res) {
            $ret = array(
                'code' => 200,
                'message' => 'ok',
            );

            return $ret;
        } else {
            $ret = array(
                'code' => 410,
                'message' => '设置失败',
            );

            return $ret;
        }
    }

    /**
     * 获取以坐席id为键，坐席名称为值的数组
     *
     * @param integer $vccId
     * @param bool    $isVerify 是否验证权限 false不验证,true验证
     *
     * @return array|bool 失败返回false，成功返回数组
     */
    public function getAgentNameKeyedByIdArray($vccId, $isVerify = false)
    {
        if (empty($vccId)) {
            return false;
        }

        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->container->get("doctrine.dbal.default_connection");
        $query = $conn->fetchAll(
            "SELECT id,ag_name,ag_num FROM win_agent WHERE is_del=0 AND vcc_id=:vcc_id",
            array(':vcc_id' => $vccId)
        );

        /** @var  $authority (数据权限) */
        $authority = array();

        if (!empty($isVerify)) {
            $authority = $this->container->get("icsoc_core.common.class")->getUserTypeCondition();
        }

        $agents = array();

        foreach ($query as $row) {
            if (!empty($isVerify) && isset($authority['ag_id'])) {
                if (in_array($row['id'], $authority['ag_id'])) {
                    $agents[$row['id']] = $row['ag_name'].' '.$row['ag_num'];
                }
            } else {
                $agents[$row['id']] = $row['ag_name'].' '.$row['ag_num'];
            }
        }

        return $agents;
    }

    /**
     * @param  integer $vccId
     *
     * @return array|bool
     */
    public function getQroupNameKeyedByIdArray($vccId)
    {
        if (empty($vccId)) {
            return false;
        }

        /** @var \Doctrine\DBAL\Connection $conn */
        $conn = $this->container->get('doctrine.dbal.default_connection');
        $query = $conn->fetchAll(
            "SELECT group_id,group_name FROM win_group WHERE is_del=0 AND vcc_id=:vcc_id",
            array(':vcc_id' => $vccId)
        );

        $groups = array();

        foreach ($query as $row) {
            $groups[$row['group_id']] = $row['group_name'];
        }

        return $groups;
    }


    /**
     * 批量添加坐席
     *
     * @param array $params    参数，格式为
     *                         array(
     *                         vcc_id,//企业id
     *                         vcc_code,//企业代码？
     *                         ag_type,//坐席id
     *                         ag_role,//原始密码
     *                         user_role,//新密码
     *                         user_type,//新密码
     *                         )
     *
     * @return array
     *
     */
    public function batchAddAgent(array $params = array())
    {
        $vccCode = empty($params['vcc_code']) ? 0 : $params['vcc_code'];
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        $insertArray['vcc_code'] = $vccCode;
        $insertArray['vcc_id'] = $vid;
        $insertArray['ag_type'] = 1;
        $insertArray['ag_role'] = isset($params['ag_role']) ? $params['ag_role'] : 1;
        $insertArray['user_role'] = isset($params['user_role']) ? $params['user_role'] : 1;
        $insertArray['user_type'] = isset($params['user_type']) ? $params['user_type'] : 1;
        if ($params['account_limit'] > 0) {
            $allAgId = array(); //收集新添加的所有坐席ID
            $conn = $this->container->get("doctrine.dbal.default_connection");
            $conn->beginTransaction();
            foreach ($params['valid_account'] as $v) {
                $insertArray['ag_num'] = $v['ag_num'];
                $insertArray['ag_name'] = $v['ag_name'];
                $insertArray['ag_nickname'] = $v['ag_nickname'];
                $insertArray['ag_password'] = md5($v['ag_password']);
                if ($params['ag_role'] == -1) {
                    //非坐席；不用判断是否超标；
                    $conn->insert('win_agent', $insertArray);
                } else {
                    if ($params['account_limit'] > 0) {
                        $conn->insert('win_agent', $insertArray);
                        $params['account_limit']--;
                    }
                }
                $allAgId[] = $lastId = $conn->lastInsertId();
                if (!empty($lastId)) {
                    if (!empty($params['user_queues'])) {
                        //添加所属技能组
                        foreach ($params['user_queues'] as $val) {
                            $parentAgent['que_id'] = $val;
                            $parentAgent['ag_id'] = $lastId;
                            $conn->insert('win_agqu', $parentAgent);
                        }
                    }
                    $insertArray['ag_id'] = $lastId;
                    $this->writeMq(array('action' => 'create', 'data' => $insertArray));
                    unset($insertArray['ag_id']);
                }
            }
            try {
                $conn->commit();
                //添加完成之后，重载坐席
                $address = $this->container->get('icsoc_core.common.class')->newGetWinIp();
                $port = $this->container->getParameter('win_socket_port');
                foreach ($allAgId as $val) {
                    $this->container->get('icsoc_data.validator')->reloadAgent($vid, $address, $val, $port);
                }
            } catch (Exception $e) {
                $conn->rollBack();

                return array('code' => '403', 'message' => '添加失败:['.$e->getMessage().']');
            }
            $this->container->get('icsoc_core.helper.logger')->actionLog(ActionLogger::ACTION_ADD, '批量新建新建用户完成');

            return array('code' => '200', 'message' => 'ok');
        } else {
            /* 已达到最大值，不能添加 */
            return array('code' => '404', 'message' => '数量已经达到最大值');
        }
    }

    /**
     * 查看是否超标； >0 可以添加， <=0 no ;
     *
     * @param integer $vccId
     *
     * @return mixed
     */
    public function agentIsOverproof($vccId)
    {
        $conn = $this->container->get("doctrine.dbal.default_connection");
        $agents = $conn->fetchColumn(
            'SELECT agents
            FROM cc_ccods
            WHERE vcc_id = :vcc_id ',
            array('vcc_id' => $vccId)
        );
        $count = $conn->fetchColumn(
            "SELECT count(*) FROM win_agent WHERE vcc_id = :vcc_id AND is_del = 0 AND ag_role <> -1",
            array('vcc_id' => $vccId)
        );

        return $agents - $count;
    }

    /**
     * 修改坐席密码接口
     *
     * @param array $params
     *
     * @return array|string
     */
    public function updatePassword(array $params = array())
    {
        $vccCode = isset($params['vcc_code']) ? $this->purifyHtml($params['vcc_code']) : '';
        $agId = isset($params['ag_id']) ? (int) $params['ag_id'] : '';
        $oldPassword = isset($params['old_password']) ? $this->purifyHtml($params['old_password']) : '';
        $newPassword = isset($params['new_password']) ? $this->purifyHtml($params['new_password']) : '';

        //vcc_code 验证
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        if (empty($agId)) {
            $ret = array(
                'code' => 403,
                'message' => '坐席ID为空',
            );

            return $ret;
        }

        if (empty($oldPassword)) {
            $ret = array(
                'code' => 405,
                'message' => '旧密码为空',
            );

            return $ret;
        }
        //新密码为空
        if (empty($newPassword)) {
            $ret = array(
                'code' => 407,
                'message' => '新密码为空',
            );

            return $ret;
        }

        //验证旧密码是否正确
        $password = $this->conn->fetchColumn(
            "SELECT ag_password FROM win_agent WHERE id=:ag_id AND vcc_id=:vcc_id ",
            array('vcc_id' => $vid, 'ag_id' => $agId)
        );
        if ($password != $oldPassword) {
            $ret = array(
                'code' => 406,
                'message' => '旧密码错误',
            );

            return $ret;
        }
        try {
            $this->conn->update(
                "win_agent",
                array('ag_password' => $newPassword),
                array('vcc_id' => $vid, 'id' => $agId)
            );
            $ret = array(
                'code' => 200,
                'message' => 'ok',
            );

            return $ret;
        } catch (Exception $e) {
            $ret = array(
                'code' => 408,
                'message' => '修改失败['.$e->getMessage().']',
            );

            return $ret;
        }
    }

    /**
     * 坐席登陆接口
     *
     * @param array $params
     *
     * @return array|string
     */
    public function siginAgent(array $params = array())
    {
        $vccCode = isset($params['vcc_code']) ? $this->purifyHtml($params['vcc_code']) : '';
        $agNum = isset($params['ag_num']) ? $this->purifyHtml($params['ag_num']) : '';
        $password = isset($params['password']) ? $this->purifyHtml($params['password']) : '';

        //vcc_code 验证
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }

        if (empty($agNum)) {
            $ret = array(
                'code' => 403,
                'message' => '坐席工号为空',
            );

            return $ret;
        }
        if (empty($password)) {
            $ret = array(
                'code' => 404,
                'message' => '密码为空',
            );

            return $ret;
        }
        $agentData = $this->conn->fetchAssoc(
            "SELECT id,ag_password,ag_status FROM win_agent WHERE vcc_code=:vcc_code
            AND ag_num=:ag_num",
            array('vcc_code' => $vccCode, 'ag_num' => $agNum)
        );
        if (empty($agentData)) {
            $ret = array(
                'code' => 405,
                'message' => '工号不存在',
            );

            return $ret;
        }
        if ($agentData['ag_status'] == 3) {
            $ret = array(
                'code' => 406,
                'message' => '您的账号被锁定，请联系管理员解除锁定',
            );

            return $ret;
        }
        if ($agentData['ag_status'] == 2) {
            $ret = array(
                'code' => 407,
                'message' => '对不起，您已离职',
            );

            return $ret;
        }
        if ($agentData['ag_password'] != $password) {
            $ret = array(
                'code' => 408,
                'message' => '坐席工号或密码错误',
                'ag_id' => $agentData['id'],
            );

            return $ret;
        }

        $result = $this->conn->fetchAssoc(
            "SELECT wa.id AS ag_id,cc.vcc_id,cc.db_main_ip,cc.db_slave_ip,cc.db_name,
            cc.db_user,cc.db_password,cc.role_action,wa.group_id,wg.group_name,
            cc.system_version,ccs.tel_addr,ccs.tel_port,ccs.addr_flash,ccs.addr_websocket
            FROM win_agent as wa
            LEFT JOIN cc_ccods AS cc
            ON cc.vcc_id = wa.vcc_id
            LEFT JOIN win_group AS wg
            ON wa.group_id = wg.group_id
            LEFT JOIN cc_cti_servers AS ccs
            ON cc.telid=ccs.telid
            WHERE wa.vcc_code=:vcc_code AND wa.ag_num=:ag_num
            AND wa.ag_password=:password AND wa.is_del=0",
            array('vcc_code' => $vccCode, 'ag_num' => $agNum, 'password' => $password)
        );

        if (empty($result)) {
            $ret = array(
                'code' => 409,
                'message' => '验证失败,没有匹配到相应数据',
            );

            return $ret;
        } else {
            $ret = array(
                'code' => 200,
                'message' => 'ok',
                'data' => $result,
            );

            return $ret;
        }
    }

    /**
     * 获取当前空闲坐席接口
     *
     * @param array $params
     *
     * @return array|string
     */
    public function freeAgent(array $params = array())
    {
        $vccCode = isset($params['vcc_code']) ? $this->purifyHtml($params['vcc_code']) : '';
        //vcc_code 验证
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        $list = $this->conn->fetchAll(
            "SELECT ag_id,pho_num,ag_name,ag_num FROM win_agmonitor WHERE ag_sta=1 AND vcc_id=:vcc_id LIMIT 1000",
            array('vcc_id' => $vid)
        );

        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'data' => $list,
        );

        return $ret;
    }

    /**
     * 获取当前通话中的坐席
     *
     * @param array $params
     *
     * @return array|string
     */
    public function onthelineAgent(array $params = array())
    {
        $vccCode = isset($params['vcc_code']) ? $this->purifyHtml($params['vcc_code']) : '';
        //vcc_code 验证
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        $list = $this->conn->fetchAll(
            "SELECT ag_id,pho_num,sec_to_time(unix_timestamp()-pho_sta_time)AS ag_time FROM win_agmonitor
             WHERE pho_sta=2 AND vcc_id=:vcc_id LIMIT 1000",
            array('vcc_id' => $vid)
        );

        $ret = array(
            'code' => 200,
            'message' => 'ok',
            'data' => $list,
        );

        return $ret;
    }

    /**
     * 设置坐席转接电话接口
     *
     * @param array $params
     *
     * @return array|string
     */
    public function agextphoneAgent(array $params = array())
    {
        $vccCode = isset($params['vcc_code']) ? $this->purifyHtml($params['vcc_code']) : '';
        $phone = isset($params['phone']) ? $this->purifyHtml($params['phone']) : '';
        $agId = isset($params['ag_id']) ? (int) $params['ag_id'] : '';
        $state = isset($params['state']) ? (int) $params['state'] : 1;
        //vcc_code 验证
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        if (empty($agId)) {
            $ret = array(
                'code' => 403,
                'message' => '坐席ID为空',
            );

            return $ret;
        }

        if (!is_numeric($agId)) {
            $ret = array(
                'code' => 404,
                'message' => '坐席ID包含非数字字符',
            );

            return $ret;
        }

        if (empty($phone)) {
            $ret = array(
                'code' => 405,
                'message' => '手机号为空',
            );

            return $ret;
        }

        if (!is_numeric($phone)) {
            $ret = array(
                'code' => 406,
                'message' => '手机号码含非数字字符',
            );

            return $ret;
        }

        if (strlen($phone) != 11) {
            $ret = array(
                'code' => 407,
                'message' => '手机号码不是11位',
            );

            return $ret;
        }

        if (!in_array($state, array(1, 0))) {
            $ret = array(
                'code' => 408,
                'message' => '状态值不是0或1',
            );

            return $ret;
        }

        //判断ag_id 是否存在
        $agent = $this->conn->fetchAssoc(
            "SELECT id FROM win_agent WHERE is_del=0 AND vcc_id=:vcc_id AND id=:ag_id",
            array('vcc_id' => $vid, 'ag_id' => $agId)
        );

        if (empty($agent)) {
            $ret = array(
                'code' => 409,
                'message' => '对应的坐席不存在',
            );

            return $ret;
        }
        try {
            $this->conn->exec(
                "INSERT INTO win_agextphone(vcc_id,ag_id,pho_num,state)
                VALUES('{$vid}','{$agId}','{$phone}','{$state}')
                ON DUPLICATE KEY UPDATE pho_num='{$phone}',state='{$state}'"
            );
            $ret = array(
                'code' => 200,
                'message' => 'ok',
            );

            return $ret;
        } catch (DBALException $e) {
            $ret = array(
                'code' => 410,
                'message' => '设置失败',
            );

            return $ret;
        }
    }

    /**
     * 设置坐席的电话是否开通呼入、呼出的权限
     *
     * @param array $params
     *
     * @return array|string
     */
    public function callstatusAgent(array $params = array())
    {
        $vccCode = isset($params['vcc_code']) ? $this->purifyHtml($params['vcc_code']) : '';
        $agId = isset($params['ag_id']) ? (int) $params['ag_id'] : '';
        $callStatus = isset($params['call_status']) ? (int) $params['call_status'] : 0;

        //vcc_code 验证
        $msg = $vid = $this->container->get('icsoc_data.validator')->checkVccCode($vccCode);
        if (!empty($msg) && is_array($msg)) {
            return $msg;
        }
        if (empty($agId)) {
            $ret = array(
                'code' => 405,
                'message' => '坐席ID为空或非数字',
            );

            return $ret;
        }

        if (!in_array($callStatus, $this->callStatus)) {
            $ret = array(
                'code' => 403,
                'message' => '呼叫状态的值不在允许的范围[0,1,2,3]内',
            );

            return $ret;
        }
        $this->conn->beginTransaction();
        $tellevel = isset($this->callStatusValue[$callStatus]) ? $this->callStatusValue[$callStatus] : 0;
        try {
            $this->conn->executeQuery(
                "UPDATE win_agent SET tellevel = (tellevel | $tellevel) WHERE id = ? AND vcc_code = ?",
                array($agId, $vccCode)
            );
            $this->conn->commit();
            $ret = array(
                'code' => 200,
                'message' => 'ok',
            );

            return $ret;
        } catch (Exception $e) {
            $this->conn->rollBack();
            $ret = array(
                'code' => 404,
                'message' => '更新失败['.implode('|', $this->conn->errorInfo()).']',
            );

            return $ret;
        }
    }

    /**
     * 把消息写入到队列
     *
     * @param array $data
     */
    public function writeMq($data)
    {
        $producer = $this->container->get('old_sound_rabbit_mq.agent_producer_producer');
        $producer->setContentType('application/json');
        $producer->publish(json_encode($data), 'manage.agent');
    }
}
